package com.coovane.bytetrix.common.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

/**
 * <p>
 *     生成traceId，方便查询线程日志
 * </p>
 *
 * @author: Hsu
 * @date: 2022/11/15 21:29
 * @copyright: companyName
 * @see
 * @since 1.8
 */
public class TraceLogUtils {

    private static String TRACE_ID = "traceId";

    private static Integer DEFAULT_LENGTH = 10;

    /**
     * 获取traceId
     * @param prefix
     * @return
     */
    public static String getTraceId(String prefix) {
        String traceId = MDC.get(TRACE_ID);
        if (StringUtils.isBlank(traceId)) {
            traceId = generateTraceId(prefix);
            MDC.put(TRACE_ID, traceId);
        }
        return traceId;
    }

    /**
     * 设置traceId，一般手动设置到异步线程中
     * @param prefix
     * @param traceId
     */
    public static void setTraceId(String prefix, String traceId) {
        if (StringUtils.isBlank(traceId)) {
            traceId = generateTraceId(prefix);
        }
        MDC.put(TRACE_ID, traceId);
    }

    public static void remove() {
        MDC.clear();
    }

    /**
     * 生成traceId
     * @param prefix
     * @return
     */
    public static String generateTraceId(String prefix) {
        return prefix + (UUIDUtils.getLowerUUID("-", "").substring(0, DEFAULT_LENGTH));
    }

}
